<?php

namespace App\Service\ChatGroup\import;

use App\Models\ChatGroup\ChatGroupFAQModel;
use App\Models\Common\ConfigModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class ChatFAQAnswer
{
    /**
     * 导入聊天群组的常见问题
     * @param Collection $collection
     * @param Command|null $command
     * @return void
     */
    public function collection(Collection $collection, ?Command $command)
    {

        // 特殊
        $special = [
            '收银机常见问题以及解决办法11.8' => 'https://file.51kuafu.com/5c/08/1589015354d16854cefe6aa5f84f8e94baa5bf22ada13f16f1bede12917d.pdf',
            '佳博D802打印机常见问题解决方法' => 'https://file.51kuafu.com/cb/da/3fd3e7f571293aec687f32f89ef02c62bc1642894d0ec0eb606d35502cfd.pdf',
        ];

        // 获得链接配置
        $sendWorkOrderArr = [];
        $sendWorkOrderConfig = ChatGroupFAQModel::getSendWorkOrder();
        foreach ($sendWorkOrderConfig as $child) {
            foreach ($child['child'] as $value) {
                if ($child['key'] == '品质异常问题') {
                    $child['key'] = '品质异常';
                }
                if ($value['key'] == '收银设备问题') {
                    $value['key'] = '收银设备';
                }
                $sendWorkOrderArr[$child['key'] . '-' . $value['key']] = $value['href'];
            }
        }

        $num       = 0;
        $collection->first()->map(function ($item) use (&$num, $sendWorkOrderArr, $special) {
            if ($num == 0) {
                $num = 1;
                return;
            }
            if ($item[1] == null) {
                return;
            }

            // 获得索引编号
            $oneId = ChatGroupFAQModel::query()->where('desc', $item[1])->value('id');

            $twoId = ChatGroupFAQModel::query()->where('desc', $item[3])->where('pid', $oneId)->value('id');

            $threeFaqModel = ChatGroupFAQModel::query()->where('desc', $item[7])->where('pid', $twoId)->first();

            if ($threeFaqModel == null) {
                return;
            }

            $answer = trim($item[10], '"');

            foreach ($sendWorkOrderArr as $question => $workOrderUrl) {
                if (strpos($answer, $question) !== false) {
                    $answer = str_replace('点击此处', ('[点击此处](' . $workOrderUrl . ')'), $answer);
                }
            }

            foreach ($special as $specialQuestion => $fileUrl) {
                if (strpos($answer, $specialQuestion) !== false) {
                    $answer = str_replace($specialQuestion, ('[' . $specialQuestion . '](' . $fileUrl . ')'), $answer);
                }
            }

            $threeFaqModel->indexNumber = $item[6];
            $threeFaqModel->answer = $answer;
            $threeFaqModel->save();
        });

    }

}
